local extension = Package:new("fsn")
extension.extensionName = "type_moon"

Fk:loadTranslationTable{
  ["fsn"] = "命运之夜"
}

--英灵卫宫 
local emiya = General:new(extension,"night__emiya","shu",4,4,General.Male)
Fk:loadTranslationTable{
  ["night"] = "夜",
  ["night__emiya"] = "卫宫",
  ["#night__emiya"] = "无名",
  ["designer:night__emiya"] = "境界の贤者",
  ["cv:night__emiya"] = "取访部顺一",
  ["illustrator:night__emiya"] = "武内崇",
}

local fsn_toei = fk.CreateActiveSkill{
  name = "fsn_toei",
  anim_type = "drawcard",
  derived_piles = "fsn_blade",
  prompt = "#fsn_toei",
  card_filter = Util.FalseFunc,
  can_use = function(self, player)
  return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and 
  player:getMark("fsn_jianzhi_on") == 0
    end,
  on_use = function(self, room, effect)
  local from = room:getPlayerById(effect.from)
  local n = from.hp
    from:drawCards(2, self.name)
    if from:isKongcheng() then return end
    local card = room:askForCard(from, 1, n, false, self.name, false, ".", "将不超过体力值的任意张手牌置于武将牌上，称为“剑”")
    self.cost_data = card
    from:addToPile("fsn_blade", self.cost_data, true, self.name)
  end,
}


local fsn_toei_start = fk.CreateTriggerSkill{
  name = "#fsn_toei_start",
  anim_type = "drawcard",
  events = {fk.EventPhaseStart},
  derived_piles = "fsn_blade",
  can_trigger = function(self, event, target, player, data)
  return 
  target == player and
  player.phase == Player.Start and #player:getPile("fsn_blade") > 0 and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_use = function(self, event, target, player, data)
  local room = player.room
  local choose = {"drawone","upgrade_heyi"}
  if player:getMark("trace_on")>0 or not player:hasSkill("fsn_heyi",true, false) then table.removeOne(choose,"upgrade_heyi")
  end
  local choice = room:askForChoice(player,choose, self.name)
  if choice == "drawone" then
  player:drawCards(1, self.name)
  elseif choice == "upgrade_heyi" then
  room:addPlayerMark(player, "trace_on") 
  end
  end,  
}

emiya:addSkill(fsn_toei)
fsn_toei:addRelatedSkill(fsn_toei_start)

Fk:loadTranslationTable{
  ["fsn_toei"] = "投影",
  [":fsn_toei"] = "出牌阶段限一次，你可以摸两张牌并将不超过体力值的任意张手牌置于武将牌上，称为“剑”；"
  .."准备阶段，若你的武将牌上有“剑”你选择一项:摸一张牌/若你拥有“鹤翼”，你可以升级“鹤翼”；若你拥有“剑制”，出牌阶段，你的“投影”失效",
  ["#fsn_toei"] = "摸两张牌，并将不超过体力值的任意张手牌置于武将牌上，称为“剑”",
  ["fsn_blade"] = "剑",
  ["drawone"] = "摸一张牌",
  ["upgrade_heyi"] = "升级“鹤翼”",
  ["#fsn_toei_start"] = "投影",
}

local huilu = fk.CreateActiveSkill{
  name = "huilu",
  anim_type = "control",
  card_num = 1,
  expand_pile = "fsn_blade",
  prompt = "#huilu",
  can_use = function(self, player)
    return #player:getPile("fsn_blade") > 0 
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Self:getPileNameOfId(to_select) == "fsn_blade"
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:moveCards({
      from = player.id,
      ids = effect.cards,
      toArea = Card.DiscardPile,
      moveReason = fk.ReasonPutIntoDiscardPile,
      skillName = self.name,
    })
  player:drawCards(1, self.name)
  if player:hasSkill("fsn_heyi",true, false) then
  room:handleAddLoseSkills(player,"-fsn_heyi", nil, true, false)
  room:handleAddLoseSkills(player,"red_bow", nil, true, false)
  elseif player:hasSkill("red_bow",true, false) then
  room:handleAddLoseSkills(player,"-red_bow", nil, true, false)
  room:handleAddLoseSkills(player,"fsn_heyi", nil, true, false)
  end 
  end,
}

Fk:loadTranslationTable{
  ["huilu"] = "回路",
  [":huilu"] = "出牌阶段，你可以弃置一张“剑”并摸一张牌，然后若你拥有“鹤翼”，你失去“鹤翼”并获得“赤弓”；若你拥有“赤弓”，你失去“赤弓”并获得“鹤翼”",
  ["#huilu"] = "弃置一张“剑”摸一张牌并切换技能",
}

emiya:addSkill(huilu)

local zhuzao = fk.CreateActiveSkill{
  name = "zhuzao",
  anim_type = "drawcard",
  prompt = "#zhuzao",
  expand_pile = "fsn_blade",
  card_num = 1,
  target_num = 1,
  can_use = function(self, player)
    return #player:getPile("fsn_blade") > 0
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Self:getPileNameOfId(to_select) == "fsn_blade"
  end,
    target_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:moveCards({
      from = player.id,
      ids = effect.cards,
      toArea = Card.DiscardPile,
      moveReason = fk.ReasonPutIntoDiscardPile,
      skillName = self.name,
    })
    local from = room:getPlayerById(effect.from)
    local cardType = { 'weapon','armor','treasure' }
    local cardTypeName = room:askForChoice(from, cardType, "zhuzao")
    local card_types = {Card.SubtypeWeapon,Card.SubtypeArmor,Card.SubtypeArmor}
    cardType = card_types[table.indexOf(cardType, cardTypeName)]
    local allCardIds = Fk:getAllCardIds()
    local allCardMapper = {}
    local allCardNames = {}
    for _, id in ipairs(allCardIds) do
      local card = Fk:getCardById(id)
      if card.type == Card.TypeEquip and card.sub_type == cardType then
        if allCardMapper[card.name] == nil then
          table.insert(allCardNames, card.name)
        end
        allCardMapper[card.name] = allCardMapper[card.name] or {}
        table.insert(allCardMapper[card.name], id)
      end
    end
    if #allCardNames == 0 then
      return
    end
    local cardName = room:askForChoice(from, allCardNames, "铸造")
    local toGain -- = room:printCard(cardName, Card.Heart, 1)
    if #allCardMapper[cardName] > 0 then
      toGain = allCardMapper[cardName][math.random(1, #allCardMapper[cardName])]
    end
    room:obtainCard(effect.tos[1], toGain, true, fk.ReasonPrey)
  end
}

emiya:addSkill(zhuzao)

Fk:loadTranslationTable{
  ["zhuzao"] = "铸造",
  [":zhuzao"] = "出牌阶段，你可以选择一名角色并弃置一张“剑”，令其获得一张你选择的非坐骑装备牌”",
  ["#zhuzao"] = "选择一名角色并弃置一张“剑”",
}

local fsn_xinxiang = fk.CreateActiveSkill{
  name = "fsn_xinxiang",
  anim_type = "drawcard",
  prompt = "#fsn_xinxiang",
  card_filter = Util.FalseFunc,
  frequency = Skill.Limited,
  can_use = function(self, player)
  return 
  #player:getPile("fsn_blade") > player.hp and 
    player:getMark("fsn_jianzhi_on") == 0
  end,
  on_use = function(self, room, effect)
  local player = room:getPlayerById(effect.from)
  local room = player.room
  local num = player.hp
  player:drawCards(num, self.name)
  room:changeMaxHp(player, 1)
  room:setPlayerMark(player, "fsn_jianzhi_on",1) 
  room:handleAddLoseSkills(player,"fsn_jianzhi", nil, true, false)
  end,
}

Fk:loadTranslationTable{
  ["fsn_xinxiang"] = "心相",
  [":fsn_xinxiang"] = "限定技 出牌阶段，若你拥有的“剑”的数量大于你的体力值，你可以摸等同于你体力值数量的牌，然后你获得“剑制”",
  ["#fsn_xinxiang"] = "摸等同于体力的牌，获得“剑制",
}

emiya:addSkill(fsn_xinxiang)

local fsn_heyi = fk.CreateTriggerSkill{
  name = "fsn_heyi",
  events = {fk.CardUseFinished},
  prompt = "#fsn_heyi",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return
    player:usedSkillTimes(self.name, Player.HistoryTurn) < 3 and
    player:hasSkill(self) and target == player and 
    data.card.trueName == "slash"
  end,
  on_cost = function(self, event, target, player, data)
    local suit = data.card:getSuitString()
    local color = ""
    if suit == "spade" or suit == "club" then
      color = "heart,diamond,nosuit"
    elseif suit == "heart" or suit == "diamond" then
      color = "spade,club,nosuit"
    else
      color = "spade,club,heart,diamond"
    end
    local pattern = "slash|.|" .. color
    local room = player.room
    local use = player.room:askForUseCard(target,"fsn_heyi",pattern,"fsn_heyi-use",true,{bypass_times = true})
    if use then
      use.extraUse = true
      self.cost_data = use
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    player.room:useCard(self.cost_data)
  end,
}

local fsn_heyi_red = fk.CreateTriggerSkill{
  name = "#fsn_heyi_red",
  anim_type = "drawcard",
  events ={fk.CardUsing},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill("fsn_heyi") and 
      ((data.card.trueName == "slash" and data.card.color == Card.Red))
  and player:getMark("trace_on")>0
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,
}

local fsn_heyi_black = fk.CreateTriggerSkill{
  name = "#fsn_heyi_black",
  anim_type = "drawcard",
  events ={fk.DamageCaused},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill("fsn_heyi") and data.card and
      ((data.card.trueName == "slash" and data.card.color == Card.Black))
  and player:getMark("trace_on")>0
  end,
  on_use = function(self, event, target, player, data)
   data.damage = data.damage + 1
  end,
}
local fsn_heyi_no = fk.CreateTriggerSkill{
  name = "#fsn_heyi_no",
  anim_type = "offensive",
  events = {fk.CardUsing},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill("fsn_heyi") and
      (data.card.trueName == "slash" and data.card.color == Card.NoColor) and player:getMark("trace_on")>0 and
      table.find(player.room:getOtherPlayers(player), function(p) return p:distanceTo(player) == 1 end)
  end,
  on_use = function(self, event, target, player, data)
    local targets = table.filter(player.room:getOtherPlayers(player), function(p) return p:distanceTo(player) == 1 end)
    if #targets > 0 then
      data.disresponsiveList = data.disresponsiveList or {}
      for _, p in ipairs(targets) do
        table.insertIfNeed(data.disresponsiveList, p.id)
      end
    end
  end,
}


fsn_heyi:addRelatedSkill(fsn_heyi_red)
fsn_heyi:addRelatedSkill(fsn_heyi_black)
fsn_heyi:addRelatedSkill(fsn_heyi_no)
emiya:addSkill(fsn_heyi)

Fk:loadTranslationTable{
  ["fsn_heyi"] = "鹤翼",
  [":fsn_heyi"] = "锁定技 1级：每回合限三次，你使用杀结算完成后，可以立刻使用一张不计入次数的异色杀"
  .."2级：每回合限三次，你使用杀结算完成后，可以立刻使用一张不计入次数的异色杀；你使用红色杀指定目标后，你可以摸一张牌，你使用黑色杀造成伤害+1，与你距离为1的角色无法响应你使用的无色杀",
  ["fsn_heyi-use"] = "鹤翼:你可以立刻使用一张颜色不同的杀，此杀不计入使用次数",
  ["#fsn_heyi_red"] = "鹤翼",
  ["#fsn_heyi_black"] = "鹤翼",
  ["#fsn_heyi_no"] = "鹤翼",
}

local red_bowFilter = fk.CreateFilterSkill{
  name = "#red_bow_filter",
  card_filter = function(self, card, player)
    return card.trueName == "slash" and
      card.name ~= "slash" and
      not player:getEquipment(Card.SubtypeWeapon) and
      player:hasSkill(self) and
      table.contains(player.player_cards[Player.Hand], card.id)
  end,
  view_as = function(self, card, player)
    local c = Fk:cloneCard("slash", card.suit, card.number)
    c.skillName = "red_bow"
    return c
  end,
}
local red_bowProhibit = fk.CreateProhibitSkill{
  name = "#red_bow_prohibit",
  prohibit_use = function(self, player, card)
    -- FIXME: 确保是因为【杀】而出闪，并且指明好事件id
    if Fk.currentResponsePattern ~= "jink" or card.name ~= "jink" or player:getMark("red_bow") == 0 then
      return false
    end
    if table.contains(player:getMark("red_bow"), card:getSuitString(true)) then
      return true
    end
  end,
}
local red_bow = fk.CreateTriggerSkill{
  name = "red_bow",
  anim_type = "offensive",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      data.card.trueName == "slash" and
      #AimGroup:getAllTargets(data.tos) == 1 and
      player:getMark("@red_bowRecord") ~= 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local logic = room.logic
    local cardUseEvent = logic:getCurrentEvent().parent
    cardUseEvent.liegong_used = true

    -- 让他不能出闪
    local to = room:getPlayerById(data.to)
    local suits = player:getMark("@red_bowRecord")
    room:setPlayerMark(to, self.name, suits)

    -- 展示牌堆顶的牌，计算加伤数量
    if #suits > 1 then
      local cards = room:getNCards(#suits - 1)
      room:moveCardTo(cards, Card.Processing, nil, fk.ReasonJustMove, self.name, nil, true, player.id)
      data.additionalDamage = data.additionalDamage or 0
      for _, id in ipairs(cards) do
        if table.contains(suits, Fk:getCardById(id):getSuitString(true)) then
          room:setCardEmotion(id, "judgegood")
          data.additionalDamage = data.additionalDamage + 1
        else
          room:setCardEmotion(id, "judgebad")
        end
        room:delay(200)
      end
      room:moveCardTo(cards, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, self.name)
    end
  end,

  refresh_events = {fk.TargetConfirmed, fk.CardUsing, fk.CardUseFinished},
  can_refresh = function(self, event, target, player, data)
    if not (target == player and player:hasSkill(self)) then return end
    local room = player.room
    if event == fk.CardUseFinished then
      return room.logic:getCurrentEvent().liegong_used
    else
      return data.card.suit ~= Card.NoSuit
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUseFinished then
      room:setPlayerMark(player, "@red_bowRecord", 0)
      for _, p in ipairs(room:getAlivePlayers()) do
        room:setPlayerMark(p, "red_bow", 0)
      end
    else
      local suit = data.card:getSuitString(true)
      local record = type(player:getMark("@red_bowRecord")) == "table" and player:getMark("@red_bowRecord") or {}
      table.insertIfNeed(record, suit)
      room:setPlayerMark(player, "@red_bowRecord", record)
    end
  end,
}

Fk:loadTranslationTable{
  ["red_bow"] = "赤弓",
  [":red_bow"] = "若你未装备武器，你的【杀】只能当作普通【杀】使用或打出。"
   .. "你使用牌时或成为其他角色使用牌的目标后，若此牌的花色未被“赤弓”记录，"
   .. "则记录此种花色。当你使用【杀】指定唯一目标后，你可以亮出牌堆顶的X张牌"
   .. "（X为你记录的花色数-1，且至少为0），然后每有一张牌花色与“赤弓”记录的"
   .. "花色相同，你令此【杀】伤害+1，且其不能使用“赤弓”记录花色的牌响应此"
   .. "【杀】。若如此做，此【杀】结算结束后，清除“赤弓”记录的花色。（其实这就是谋烈弓）",
  ["@red_bowRecord"] = "赤弓",
  ["#red_bow_filter"] = "赤弓",
}

red_bow:addRelatedSkill(red_bowFilter)
red_bow:addRelatedSkill(red_bowProhibit)
emiya:addRelatedSkill(red_bow)

local fsn_jianzhi = fk.CreateTriggerSkill{
  name = "fsn_jianzhi",
  anim_type = "offensive",
  events = {fk.CardUseFinished},
  derived_piles = "fsn_blade",
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
  return 
  target ~= player and #player:getPile("fsn_blade") > 0  and 
  player:getMark("fsn_jianzhi_on") == 1
  end,
  on_cost = function(self, event, target, player, data)
    local card = player.room:askForCard(player, 1, 1, false, self.name, true,
      ".|.|.|fsn_blade|.|.", "#jianzhi-invoke::"..target.id, "fsn_blade")
    if #card > 0 then
      self.cost_data = card
      return true
    end
   end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:doIndicate(player.id, {target.id})
    room:moveCards({
      from = player.id,
      ids = self.cost_data,
      toArea = Card.DiscardPile,
      moveReason = fk.ReasonPutIntoDiscardPile,
      skillName = self.name,
      specialName = self.name,
    })
    player:drawCards(1, self.name)
    local slash = Fk:cloneCard("slash")
    slash.skillName = self.name
    if player:prohibitUse(slash) then return false end
    local max_num = slash.skill:getMaxTargetNum(player, slash)
    if max_num == 0 then return false end
    local targets = {}
    for _, p in ipairs(room.alive_players) do
      if not (p == player or player:isProhibited(p, slash)) then
        table.insert(targets, p.id)
      end
    end
    if #targets == 0 then return false end
    local tos = room:askForChoosePlayers(player, targets, 1, max_num, "#jianzhi-slash:::" .. max_num, self.name, true, true)
    if #tos > 0 then
      room:useCard({
        from = player.id,
        tos = table.map(tos, function(pid) return { pid } end),
        card = slash,
        extraUse = true,
      })
    end
    end,
}

local fsn_jianzhi_end = fk.CreateTriggerSkill{
  name = "#fsn_jianzhi_end",
  anim_type = "drawcard",
  events = {fk.TurnEnd},
  frequency = Skill.Compulsory,
  derived_piles = "fsn_blade",
  can_trigger = function(self, event, target, player, data)
  return 
  target == player and
  #player:getPile("fsn_blade") == 0 and    player:getMark("fsn_jianzhi_on") == 1
  end,
  on_use = function(self, event, target, player, data)
  local room = player.room
  room:changeMaxHp(player, -2)
  room:setPlayerMark(player, "fsn_jianzhi_on",0)
  player:addSkillUseHistory("fsn_xinxiang", -1)
  room:handleAddLoseSkills(player,"-fsn_jianzhi", nil, true, false)
  end,  
}

local fsn_jianzhi_maxcards = fk.CreateMaxCardsSkill{
  name = "#fsn_jianzhi_maxcards",
  correct_func = function(self, player)
    if player:hasSkill(self) then
      return #player:getPile("fsn_blade")
    else
      return 0
    end
  end,
}

Fk:loadTranslationTable{
  ["fsn_jianzhi"] = "剑制",
  [":fsn_jianzhi"] = "锁定技 其他角色使用牌结算后，你可以弃置一张“剑”并摸一张牌，然后你使用一张无距离限制的杀，此杀不计入使用次数；结束阶段，若你的武将牌上没有“剑“，你减少两点体力上限并失去“剑制”，然后你重置“心相”；你的手牌上限+x（x为“剑”的数量）",
  ["#fsn_jianzhi_end"] = "剑制",
  ["#fsn_jianzhi_maxcards"] = "剑制",
  ["#jianzhi-invoke"] = "剑制：你可以弃置一张“剑”并摸一张牌",
  ["#jianzhi-slash"] = "剑制：你可以使用一张无距离限制的杀，此杀不计入使用次数",
}

fsn_jianzhi:addRelatedSkill(fsn_jianzhi_maxcards)
fsn_jianzhi:addRelatedSkill(fsn_jianzhi_end)
emiya:addRelatedSkill(fsn_jianzhi)

return extension
